package com.freshmarket.freshmarket.controller;


import com.freshmarket.freshmarket.entity.Manager;
import com.freshmarket.freshmarket.exception.MyException;
import com.freshmarket.freshmarket.service.IManagerService;
import com.freshmarket.freshmarket.utils.EncryptUtil;
import com.freshmarket.freshmarket.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 *  后端控制器
 * </p>
 *
 * @author Squirrel
 * @since 2020-09-04
 */
@Controller
@RequestMapping("/freshmarket/manager")
@Slf4j
public class ManagerController {
    @Autowired
    private IManagerService iManagerService;
    /**
     * 管理员登录
     */
    @RequestMapping("login")
    @ResponseBody
    public Result login(@RequestParam("managerName")String managerName,
                        @RequestParam("managerPassword")String managerPassword,HttpServletRequest request) throws Exception {

        log.info("管理员：{}"+managerName);
        //String pws = EncryptUtil.encrypt(managerPassword);
        //System.out.println(pws);
            Subject subject = SecurityUtils.getSubject();

            subject.login(new UsernamePasswordToken(managerName,managerPassword));

            String nowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            Result result = iManagerService.updateManagerLoginTime(managerName, nowDate);
            return result;

    }
    //管理员注册
    @PostMapping("register")
    @ResponseBody
    public Result register(@RequestParam("managerName") String managerName,@RequestParam("managerPassword") String managerPassword) throws Exception {
        log.info("注册的用户：{}"+managerName);
        Manager manager = new Manager();
        manager.setManagerName(managerName);

        String pws = EncryptUtil.encrypt(managerPassword);
        manager.setManagerPassword(pws);
        Result result = iManagerService.insertManager(manager);
        return result;
    }
    /*//管理员登出
    @GetMapping("logout")

    public String logout(HttpServletRequest request){
        request.getSession().invalidate();
        System.out.println("haha"+request.getSession().getId());
        return "redirect:/loginer";
    }*/
}

